package com.xja.seckill.users.service.impl;

import com.xja.seckill.order.commons.JsonBean;
import com.xja.seckill.users.domain.mapper.UsersMapper;
import com.xja.seckill.users.domain.model.Users;
import com.xja.seckill.users.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.UUID;

@Service
public class UsersServiceImpl implements UsersService {

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public JsonBean login(String username, String password, HttpServletRequest request) {

        Users users = usersMapper.selectByUserName (username);
        if (username==null || password==null){
            return new JsonBean(-1,"用户名或密码为空",null);
        }
        if (!users.getPassword ().equals (password)) {
            return new JsonBean(-1,"密码错误",null);
        }
        HttpSession session = request.getSession ();
        session.setAttribute ("username",username);
        return new JsonBean(0,"登陆成功",null);
    }

    @Override
    public JsonBean registered(Users users) {
        if (users.getPassword ()==null || users.getUsername ()==null ){
            return new JsonBean (-1,"未设置用户名或密码",null);
        }
        if (usersMapper.selectByUserName (users.getUsername ())!=null ){
            return new JsonBean (-1,"注册失败，用户已存在",null);
        }
        String token = UUID.randomUUID ().toString ().replace ("-", "").substring (0, 10);
        users.setToken (token);
        usersMapper.insert (users);
    return new JsonBean(0,"注册成功",null);
    }
}
